class FriendsBetController < ApplicationController
  def index
    @sid = params[:sid]
    metch = Match.find(@sid)
    uid = params[:fb_sig_user]
    @user = User.find(uid)
    @home_friends = metch.bets.home_friends(@user.all_friends).map{|b| b.user}
    @away_friends = metch.bets.away_friends(@user.all_friends).map{|b| b.user}
    @other_friends = User.find(:all,:conditions=>"id in (#{@user.all_friends})") - @home_friends - @away_friends
    render :partial=>'index',:locals=>{:sid=>@sid,:user=>@user}
  end

  def sent
    if User.find(params[:fb_sig_user]).point > params[:amount].to_i 
      @to_user = User.find(params[:to_user_id])
      ch = Challenge.new
      ch.from_user_id = params[:fb_sig_user]
      ch.to_user_id   = params[:to_user_id]
      ch.amount       = params[:amount]
      ch.message      = params[:message]
      ch.match_id     = params[:sid]
      ch.mode         = "bet_0"
      ch.save

      ch.sender.point = ch.sender.point - ch.amount.to_i 
      ch.sender.save
      PointHistory.create(:user_id=>ch.sender.id,:action=>'place challenge bet winpoints ' + ch.match.info,:point=>ch.amount,:earning => false)

      NotificationPublisher.deliver_challenge_notify(ch)
      NotificationPublisher.deliver_challenge_email(ch)
      @error = nil
    else
      @error = "Not enough WinPoints to make this challenge."
    end
    render :partial=>'sent'
  end
  def gen_dialog
    sid= params[:sid]
    uid = params[:fb_sig_user]
    u = nil
    u = User.find(params[:uid]) if params[:uid]
    ch = Challenge.find(params[:chid]) if params[:chid]
    metch = Match.find(sid)
    @user = User.find(uid)
    @home_friends = metch.bets.home_friends(@user.all_friends).map{|b| b.user}
    @away_friends = metch.bets.away_friends(@user.all_friends).map{|b| b.user}
    @other_friends = User.find(:all,:conditions=>"id in (#{@user.all_friends})") - @home_friends - @away_friends
    if ch
      render :partial=>'place_challenge_form',:locals=>{:sid=>sid,:u=>u,:ch=>ch}
    else
      render :partial=>'place_challenge_form',:locals=>{:sid=>sid,:u=>u}
    end
  end
  def accept
    ch =  Challenge.find(params[:chid])
    @error = nil
    if ch.goter.point > ch.amount.to_i 
      ch.mode = "bet_1"
      ch.save
      ch.goter.point = ch.goter.point - ch.amount 
      ch.goter.save
      PointHistory.create(:user_id=>ch.goter.id,:action=>'Accept challenge bet winpoints ' + ch.match.info,:point=>ch.amount,:earning => false)

    else
      @error = "Not enough WinPoints to accept this challenge."
    end
    render :partial=>'accept'
  end

  def all
    @chs  = current_user.sent_challenges
  end
  def destroy
    @buy_win = BuyWin.find(params[:id])
    @buy_win.destroy

    respond_to do |format|
      format.fbml { redirect_to(buy_wins_url) }
      format.xml  { head :ok }
    end
  end
end
